from pyppeteer import launch
import asyncio
import redis
import time

async def login(keyword):
    browser =await launch(headless=False)
    page = await browser.newPage()
    await page.setUserAgent(userAgent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36')
    js1 = '''() =>{
                Object.defineProperties(navigator,{
                webdriver:{
                    get: () => undefined
                    }
                })
            }'''
    js2 = '''() => {
                    window.navigator.webdriver
            }'''
    await page.goto('https://www.toutiao.com/ch/{0}/'.format(keyword))
    await page.evaluate(js1)
    await page.evaluate(js2)
    while True:
        t = int(time.time())
        try:
            _signature=await page.evaluate('''
            TAC.sign({0});
        '''.format(t))  #获取签证
            await sent_msg(t,_signature)
            await asyncio.sleep(1)
        except:
            break
    await asyncio.sleep(100)
    await browser.close()

async def sent_msg(t,_signature):
    ajax_url = 'https://www.toutiao.com/api/pc/feed/?category=news_tech&utm_source=toutiao&widen=1&max_behot_time={0}&max_behot_time_tmp={1}&tadrequire=true&_signature={2}'.format(t,t,_signature)
    conn.rpush(QUEUE,ajax_url)
    return True

if __name__ == '__main__':
    keyword = input('输入新闻类型:')
    #连接redis
    conn = redis.Redis('106.14.144.54', port=6379, db=0, password='Wzl!13433627612')
    QUEUE = keyword
    asyncio.get_event_loop().run_until_complete(login(keyword))